﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace OS
{
    class CardReader
    {
        private const string FILE_PATH = "AllProgramsPhase3.txt";

        public static bool endOfFile;
        public static string backup = null;
        private String programID;
        public static StreamReader reader = new StreamReader(FILE_PATH);

        /// <summary>
        /// Getter/setter for programID
        /// </summary>
        public String ProgramID
        {
            get { return programID; }
            set { programID = value; }
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        public CardReader()
        {
            endOfFile = false;
        }//end default constructor

        /// <summary>
        /// Reads in the next card from the file
        /// </summary>
        /// <returns>The card read from the file</returns>
        public static String ReadNextCard()
        {
            return reader.ReadLine();
        }

        private static void AddInstructionsToMemory(ProcessControlBlock pcb, string instrLine)
        {
            Trace.WriteToTrace("Program card " + instrLine + " read.");
            string line = instrLine;

            int location = 0;
            bool freeBlockFound = false;
            Random random = new Random();

            while (!freeBlockFound)
            {
                location = random.Next(0, 29) * 10;
                
                if (UserStorage.PhysicalMemory[location, 0] != null)
                {
                    location = random.Next(0, 29) * 10;
                }
                else
                {
                    freeBlockFound = true;
                }
            }

            Trace.WriteToTrace("Frame for control card stored in the page table");

            for(int i = 0; i < 10; i++)
            {
                if (UserStorage.PhysicalMemory[pcb.register_PTR + i, 0].Equals(" "))
                {
                    UserStorage.PhysicalMemory[pcb.register_PTR + i, 0] = Convert.ToString(location);
                    break;
                }
            }

            Trace.WriteToTrace("Program card stored in frame " + location / 10);
            
            //add each instruction to memory
            for (int i = 0; i < 10; i++)
            {
                while(line.Length < 4)
                {
                    line += " ";
                }

                string temp = line.Substring(0, 4);

                for (int j = 0; j < temp.Length; j++)
                {
                    UserStorage.PhysicalMemory[location, j] = Convert.ToString(temp[j]);
                }

                location++;
                line = line.Substring(4);
            }
        }
    }
}